import { axiosInstance } from 'src/boot/axios'
import CommonConfig from 'src/assets/js/config'
import qs from 'qs'
import _ from 'lodash'
const baseUrlDispatch = CommonConfig.planningUrl
const baseUrlSchema = CommonConfig.schemaUrl
const baseUrlTpm = CommonConfig.tpmUrl

const qsConfig = {
  arrayFormat: 'repeat',
  skipNulls: true,
  format: 'RFC3986'
}

// 列举车间计划
export function getPlantPlanList (keyword, pageNum, pageSize, searchBy, dispatchingStatus, startDate, endDate) {
  const newUrl = `${baseUrlDispatch}/v3/workshop_plannings/dispatchable/simple`

  let reqData = {
    params: {
      dispatchingStatus,
      keyword: keyword || undefined,
      pageNum,
      pageSize,
      searchBy: searchBy || undefined,
      startDate,
      endDate
    }
  }
  return axiosInstance.get(newUrl, reqData).then((res) => {
    return Promise.resolve(res)
  })
}

// 列举车间详细计划(工序计划)
export function getProcessPlanList (planningId) {
  const newUrl = `${baseUrlDispatch}/v3/workshop_plannings/dispatchable/${planningId}`

  return axiosInstance.get(newUrl).then((res) => {
    return Promise.resolve(res)
  })
}

// 列举设备类型
export function getDict (code, disable) {
  const newUrl = baseUrlSchema + '/v1/dict_by_gcode'
  const params = {
    dicGroupCode: code,
    disable: disable
  }

  return axiosInstance.get(newUrl, { params }).then((res) => {
    return Promise.resolve((res))
  })
}

// 获取车间
export function getWorkshops (plantId) {
  const newUrl = `${baseUrlSchema}/v1/workshop_kv`
  const params = {
    plantId,
    withPlantName: false
  }

  return axiosInstance.get(newUrl, { params }).then((res) => {
    return Promise.resolve((res))
  })
}

// 列举车间设备
export function getMachine (params, workshopId) {
  if (_.isNil(workshopId)) {
    return
  }
  const newUrl = `${baseUrlTpm}/v1/workshops/${workshopId}/devices`

  let reqData = {
    params
  }
  return axiosInstance.get(newUrl, reqData).then((res) => {
    return Promise.resolve(res.data)
  })
}

// 根据车间和年月日查询排班
export function getShifts (workshopId, start, end) {
  if (_.isNil(workshopId)) {
    return
  }
  const newUrl = `${baseUrlSchema}/v1/workshops/${workshopId}/shifts:byPeriod`

  let reqData = {
    params: {
      since: start || undefined,
      before: end || undefined
    }
  }
  return axiosInstance.get(newUrl, reqData).then((res) => {
    return Promise.resolve(res)
  })
}

// 列举工单
export function getWorkOrders (params) {
  const newUrl = `${baseUrlDispatch}/v4/work_orders/dispatching`

  let reqData = {
    params,
    paramsSerializer: function (params) {
      return qs.stringify(params, qsConfig)
    }
  }
  return axiosInstance.get(newUrl, reqData).then((res) => {
    return Promise.resolve(res)
  })
}

// 新增工单
export function addWorkOrder (query) {
  const url = `${baseUrlDispatch}/v3/process_plannings/${query.processPlanningId}/work_orders`

  return axiosInstance.post(url, query).then(resp => {
    return Promise.resolve(resp)
  })
}

// 锁定工单
export function lockWorkOrder (groupId) {
  const url = `${baseUrlDispatch}/v4/groups/${groupId}/work_orders/movability`

  return axiosInstance.delete(url).then(res => {
    return Promise.resolve(res)
  })
}

// 解锁工单
export function unLockWorkOrder (groupId) {
  const newUrl = `${baseUrlDispatch}/v4/groups/${groupId}/work_orders/movability`

  return axiosInstance.post(newUrl).then(res => {
    return Promise.resolve(res)
  })
}

// 列举某工序派工的工单记录
export function getWorkOrderLog (processPlanningId) {
  const newUrl = `${baseUrlDispatch}/v3/process_plannings/${processPlanningId}/work_orders/dispatching`

  return axiosInstance.get(newUrl).then(res => {
    return Promise.resolve(res)
  })
}

// 删除工单
export function delWorkOrder (workOrderId) {
  const url = `${baseUrlDispatch}/v4/groups/${workOrderId}/work_orders`

  return axiosInstance.delete(url).then(res => {
    return Promise.resolve(res)
  })
}

// 一键撤销
export function revokeWorkOrder (workshopPlanningId) {
  const url = `${baseUrlDispatch}/v3/work_orders/revoke/${workshopPlanningId}`

  return axiosInstance.delete(url).then(res => {
    return Promise.resolve(res)
  })
}
// 批量删除工单
export function batchDelWorkorder (workOrderIds) {
  let reqData = {
    params: {
      groupIds: workOrderIds
    },
    paramsSerializer: function (params) {
      return qs.stringify(params, qsConfig)
    }
  }

  const url = `${baseUrlDispatch}/v4/groups/work_orders:batchDelete`
  return axiosInstance.delete(url, reqData).then((res) => {
    return Promise.resolve((res))
  })
}

// 列举未完成工单
export function getNotFinishedOrders (params) {
  let reqData = {
    params,
    paramsSerializer: function (params) {
      return qs.stringify(params, qsConfig)
    }
  }
  const newUrl = `${baseUrlDispatch}/v1/not_finished/work_orders/devices`

  return axiosInstance.get(newUrl, reqData).then(res => {
    return Promise.resolve(res.data)
  })
}
// 列举设备下未完成工单
export function getNotFinishedOrdersById (deviceId) {
  const newUrl = `${baseUrlDispatch}/v4/devices/${deviceId}/not_finished/work_orders`

  return axiosInstance.get(newUrl).then(res => {
    return Promise.resolve(res.data)
  })
}

// 移动工单到另一个设备排班
export function moveWorkOrderToAnotherDeviceScheduling (workOrderId, workshopId, shiftId, date,
  deviceId) {
  const url = `${baseUrlDispatch}/v3/work_orders/${workOrderId}/device_scheduling`

  const data = {
    workshopId,
    deviceId,
    shiftId,
    date
  }

  return axiosInstance.put(url, data)
}

/**
 * @typedef RearrangingNewPeriod
 * @type {{}}
 * @property {number|string} id 工单 ID
 * @property {string} newStartTime 新的开始时间（ISO 8601）
 * @property {string} newEndTime 新的结束时间（ISO 8601）
 */

/**
 * 移动工单到当班其他时间
 *
 * @param {number|string} deviceId 设备 ID
 * @param {string} date 排班所在日期（ISO 8601）
 * @param {number|string} shiftId 班制 ID
 * @param {RearrangingNewPeriod[]} newPeriods 新的工单开始结束时间
 * <p>
 * 数组中必须包含当班所有的工单
 * @returns {Promise} promise
 */
export function rearrangeDeviceSchedulingWorkOrders (deviceId, date, shiftId, newPeriods) {
  const url = `${baseUrlDispatch}/v4/devices/${deviceId}/${date}/shifts/${shiftId}/work_orders` +
    '/periods'

  const data = {
    workOrders: newPeriods
  }

  return axiosInstance.put(url, data)
}

// 根据班制和设备获取工单列表
export function getWorkOrdersByDeviceShifts (deviceId, shiftId, params) {
  const newUrl = `${baseUrlDispatch}/v4/devices/${deviceId}/shifts/${shiftId}/work_orders`

  return axiosInstance.get(newUrl, { params }).then(res => {
    return Promise.resolve(res.data)
  })
}

// 根据班制和设备获取工单列表
export function getLastWorkOrder (deviceIds, productId, processInfoId) {
  const newUrl = `${baseUrlDispatch}/v1/devices/products/${productId}/process_infos/${processInfoId}/last/work_order`
  // let params = {
  //   deviceIds: deviceIds
  // }
  return axiosInstance.post(newUrl, deviceIds).then(res => {
    return Promise.resolve(res.data)
  })
}

// 批量调度获取设备
export function getDevices (workshopId, workDate, shiftId) {
  const newUrl = `${baseUrlTpm}/v1/workshops/${workshopId}/lines/devices`
  let reqData = {
    params: {
      workDate,
      shiftId
    }
  }
  return axiosInstance.get(newUrl, reqData).then((res) => {
    return Promise.resolve(res.data)
  })
}
// 解锁工单
export function batchCreateWorkOrder (processPlanningId, params) {
  const newUrl = `${baseUrlDispatch}/v4/process_plannings/${processPlanningId}/work_orders`

  return axiosInstance.post(newUrl, params).then(res => {
    return Promise.resolve(res)
  })
}
// 列举设备
export function getDeviceIds (schemeId, schemeLevel) {
  const newUrl = `${baseUrlTpm}/v1/devices`
  const reqData = {
    params: {
      schemeLevel,
      schemeId
    }
  }
  return axiosInstance.get(newUrl, reqData).then((res) => {
    return Promise.resolve((res))
  })
}

// 列举工单详情
export function getOrderDetail (groupId) {
  const newUrl = `${baseUrlDispatch}/v4/groups/${groupId}/work_orders/details`
  return axiosInstance.get(newUrl).then((res) => {
    return Promise.resolve(res.data)
  })
}

// 列举组合工单所选车间计划
export function combinedWorkshopPlannings (params) {
  const reqData = {
    params,
    paramsSerializer: function (params) {
      return qs.stringify(params, qsConfig)
    }
  }
  const newUrl = `${baseUrlDispatch}/v1/combined_workshop_plannings`
  return axiosInstance.get(newUrl, reqData).then((res) => {
    return Promise.resolve(res.data)
  })
}

// 创建组合工单
export function createCombinedWorkOrder (params) {
  const newUrl = `${baseUrlDispatch}/v4/combined_work_orders`
  return axiosInstance.post(newUrl, params).then((res) => {
    return Promise.resolve(res)
  })
}
// 工序计划强制关闭
export function closePlanning (id) {
  const url = `${baseUrlDispatch}/v1/process_plannings/forced_close/${id}`

  return axiosInstance.patch(url).then(res => {
    return Promise.resolve(res)
  })
}
